package com.zyk.shiro;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.zyk.entity.Resource;
import com.zyk.entity.Role;
import com.zyk.entity.User;
import com.zyk.service.*;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.web.filter.mgt.DefaultFilter;
import org.apache.velocity.runtime.directive.Foreach;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static org.apache.shiro.web.filter.mgt.DefaultFilter.user;

/**
 * Created by Administrator on 2017/11/14.
 */
public class UserRealm extends AuthorizingRealm{

    private String salt = "test";

    @Autowired
    private IUserService userService;

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IResourceService resourceService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //授权的时候放入的是user对象，取的时候可以直接墙砖为对象
        User user  = (User) principalCollection.getPrimaryPrincipal();
        //存放role的id
        List<Role> roleList = roleService.selectRoleIdListByUserId(user.getId());
        List<Long> roleIdList = new ArrayList();
        //存放role的角色名
        Set<String> roleNameList = new HashSet<String>();
        for (Role role : roleList) {
            roleIdList.add(role.getId());
            roleNameList.add(role.getName());
        }
        //根据roleId获取所有的resouce
        List<Resource> resourcesList = resourceService.selectResourceListInRoleId(roleIdList);
        Set<String> urlSet =new HashSet<String>();
        for (Resource r:resourcesList) {
            urlSet.add(r.getUrl());
        }
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        info.setRoles(roleNameList);//添加角色
        info.setStringPermissions(urlSet);//添加权限
        return info;
    }
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username = (String) authenticationToken.getPrincipal();
        User user = userService.selectOne(new EntityWrapper<User>(new User(username)));
        return new SimpleAuthenticationInfo(user, user.getPassword(), ByteSource.Util.bytes(salt), getName());
    }
}





















